package com.ztom.top100;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 接雨水
 * <p>
 * https://leetcode-cn.com/problems/trapping-rain-water/
 *
 * @author ZhangTao
 */
public class Code20Trap {

    /**
     * 单调栈解法
     *
     * @param height
     * @return
     */
    public int trap(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }

        int res = 0;
        // 单调栈
        Deque<Integer> stack = new LinkedList<>();
        for (int i = 0; i < height.length; i++) {
            while (!stack.isEmpty() && height[stack.peekLast()] < height[i]) {
                Integer top = stack.pollLast();
                if (stack.isEmpty()) {
                    break;
                }
                int l = stack.peekLast();
                int r = i;
                int width = r - l - 1;
                int high = Math.min(height[l], height[r]) - height[top];
                res += width * high;
            }
            stack.addLast(i);
        }

        return res;
    }

    /**
     * 双指针解法
     *
     * @param height
     * @return
     */
    public int trap2(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }
        int res = 0;

        int l = 0, r = height.length - 1;
        int lmax = 0, rmax = 0;
        while (l < r) {
            lmax = Math.max(lmax, height[l]);
            rmax = Math.max(rmax, height[r]);
            if (height[l] < height[r]) {
                res += lmax - height[l++];
            } else {
                res += rmax - height[r--];
            }
        }

        return res;
    }
}
